package com.llxwz.service;


import com.llxwz.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
    * @Description: 点赞
    * @Param: [userId谁点的赞, entityType被点赞的实体,
     *          entityId被点赞的实体的id, entityUserId被点赞的实体的作者id]
    * @return: void
    * @Author: zb
    * @Date: 2022/6/6
    */

    public void like(int userId, int entityType, int entityId, int entityUserId) {
        //编程式事务
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                //拼接被点赞实体的key
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                //拼接被点赞的实体的作者的key
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
                //判断某用户点过赞没？判断依据是set集合里是否有userId
                boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);
                //开启事务
                operations.multi();

                if (isMember) {//点过赞
                    operations.opsForSet().remove(entityLikeKey, userId);
                    //减少用户收到的赞的数量
                    operations.opsForValue().decrement(userLikeKey);
                } else {
                    operations.opsForSet().add(entityLikeKey, userId);
                    //增加用户收到的赞的数量
                    operations.opsForValue().increment(userLikeKey);
                }
                //提价事务
                return operations.exec();
            }
        });
    }

    // 查询某实体被点赞的数量
    public long findEntityLikeCount(int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    // 查询某人对某实体的点赞状态（已赞或未赞）
    public int findEntityLikeStatus(int userId, int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

    // 查询某个用户获得的赞的数量
    public int findUserLikeCount(int userId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count.intValue();
    }

}
